package com.oxygen.pt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.oxygen.pt.mapper.OxygenChamberInspectionDailyMapper;
import com.oxygen.pt.pojo.dto.OxygenChamberInspectionSaveDTO;
import com.oxygen.pt.pojo.entity.OxygenChamberInspection;
import com.oxygen.pt.pojo.vo.InspectionSimpleVO;
import com.oxygen.pt.pojo.vo.OxygenChamberInspectionPageVO;
import com.oxygen.pt.service.OxygenChamberInspectionService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class OxygenChamberInspectionServiceImpl implements OxygenChamberInspectionService {

    @Resource
    private OxygenChamberInspectionDailyMapper inspectionDailyMapper;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public boolean deleteById(Long id) {
        return inspectionDailyMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(OxygenChamberInspectionSaveDTO dto) throws JsonProcessingException {
        // 1. 日期已存在直接返回 false，不抛异常
        // 2. TODO：联合主键（日期、氧舱号）
        if (inspectionDailyMapper.existsByInspectDate(dto.getInspectDate())) {
            return false;
        }
        String remarksJson = BuildRemarkJSON(dto);
        // 3. 构造实体并持久化
        OxygenChamberInspection entity = BeanUtil.copyProperties(dto, OxygenChamberInspection.class);
        entity.setRemarks(remarksJson);
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());
        return inspectionDailyMapper.insert(entity) > 0;
    }

    private String BuildRemarkJSON(OxygenChamberInspectionSaveDTO dto) throws JsonProcessingException {
        Map<String, String> remarkMap = new LinkedHashMap<>(7);
        remarkMap.put("powerSupply",     defaultEmpty(dto.getPowerSupplyRemark()));
        remarkMap.put("computerSystem",  defaultEmpty(dto.getComputerSystemRemark()));
        remarkMap.put("lightingSystem",  defaultEmpty(dto.getLightingSystemRemark()));
        remarkMap.put("oxygenDevice",    defaultEmpty(dto.getOxygenDeviceRemark()));
        remarkMap.put("meterStatus",     defaultEmpty(dto.getMeterStatusRemark()));
        remarkMap.put("flowSwitch",      defaultEmpty(dto.getFlowSwitchRemark()));
        remarkMap.put("electricParts",   defaultEmpty(dto.getElectricPartsRemark()));
        String remarksJson;
        remarksJson = new ObjectMapper().writeValueAsString(remarkMap);
        return remarksJson;
    }

    /*
    为方便，此处的service不设置新的VO使用OxygenChamberInspectionSaveDTO作为返回，属性完全相同
     */
    @Override
    public OxygenChamberInspectionSaveDTO findById(Long id) {

        OxygenChamberInspection entity = inspectionDailyMapper.selectById(id);

        if (entity == null) {
            return null;
        }

        OxygenChamberInspectionSaveDTO dto = new OxygenChamberInspectionSaveDTO();

        // 1. 基础字段
        dto.setInspectDate(entity.getInspectDate());
        dto.setInspector(entity.getInspector());

        // 2. 7 个状态
        dto.setPowerSupply(entity.getPowerSupply());
        dto.setComputerSystem(entity.getComputerSystem());
        dto.setLightingSystem(entity.getLightingSystem());
        dto.setOxygenDevice(entity.getOxygenDevice());
        dto.setMeterStatus(entity.getMeterStatus());
        dto.setFlowSwitch(entity.getFlowSwitch());
        dto.setElectricParts(entity.getElectricParts());

        // 3. 解析 remarks JSON -> Map
        Map<String, String> remarkMap = parseRemarks(entity.getRemarks());
        dto.setPowerSupplyRemark(remarkMap.getOrDefault("powerSupply", ""));
        dto.setComputerSystemRemark(remarkMap.getOrDefault("computerSystem", ""));
        dto.setLightingSystemRemark(remarkMap.getOrDefault("lightingSystem", ""));
        dto.setOxygenDeviceRemark(remarkMap.getOrDefault("oxygenDevice", ""));
        dto.setMeterStatusRemark(remarkMap.getOrDefault("meterStatus", ""));
        dto.setFlowSwitchRemark(remarkMap.getOrDefault("flowSwitch", ""));
        dto.setElectricPartsRemark(remarkMap.getOrDefault("electricParts", ""));

        return dto;
    }

    @Override
    public List<OxygenChamberInspectionPageVO> pageByDateRange(LocalDate start, LocalDate end) {
        return inspectionDailyMapper.selectPageByDateRange(start, end);
    }

    @Override
    public boolean update(OxygenChamberInspectionSaveDTO dto, Long id) throws JsonProcessingException {
        // 1. 构造 remarks JSON（复用之前逻辑）
        String remarksJson = BuildRemarkJSON(dto);
        // 2. 构造实体
        OxygenChamberInspection record = new OxygenChamberInspection();
        record.setId(id);
        record.setInspectDate(dto.getInspectDate());
        record.setInspector(dto.getInspector());
        record.setPowerSupply(dto.getPowerSupply());
        record.setComputerSystem(dto.getComputerSystem());
        record.setLightingSystem(dto.getLightingSystem());
        record.setOxygenDevice(dto.getOxygenDevice());
        record.setMeterStatus(dto.getMeterStatus());
        record.setFlowSwitch(dto.getFlowSwitch());
        record.setElectricParts(dto.getElectricParts());
        record.setRemarks(remarksJson);

        // 3. 执行更新
        return inspectionDailyMapper.updateById(record) > 0;
    }

    private String defaultEmpty(String s) {
        return s == null ? "" : s.trim();
    }

    private static Map<String, String> parseRemarks(String json) {
        if (json == null || json.trim().isEmpty()) {
            return Collections.emptyMap();
        }
        try {
            return MAPPER.readValue(json, new TypeReference<>() {});
        } catch (Exception e) {
            // 日志可打在这里
            return Collections.emptyMap();
        }
    }

    @Override
    public List<InspectionSimpleVO> listAllForExport() {
        //System.out.println(Arrays.stream(inspectionSimpleVOS.toArray()).toList().toString());
        return inspectionDailyMapper.listCurrentMonthForExport();
    }

}
